package com.example.hello;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;

import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.time.LocalDate;

public class MoneyActivity extends AppCompatActivity implements Runnable{
    private static final String TAG = "MoneyActivity";

    EditText rmb;
    TextView result;
    float dollarRate;
    float euroRate;
    float wonRate;
    Handler handler;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_money);
        rmb=findViewById(R.id.rmb);
        result=findViewById(R.id.result);
        /*
        Intent intent =getIntent();
        dollarRate=intent.getFloatExtra("dollar_key1",1f);
        euroRate=intent.getFloatExtra("euro_key1",2f);
        wonRate=intent.getFloatExtra("won_key1",3f);

        */
        SharedPreferences sharedPreferences=getSharedPreferences("myrate",MoneyActivity.MODE_PRIVATE);

        dollarRate=sharedPreferences.getFloat("dollar_rate",0.1533f);
        euroRate=sharedPreferences.getFloat("euro_rate",0.1282f);
        wonRate=sharedPreferences.getFloat("won_rate",171.25f);
        Log.i(TAG,"onCreate:dollar="+dollarRate);
        Log.i(TAG,"onCreate:euro="+euroRate);
        Log.i(TAG,"onCreate:won="+wonRate);

        String updateStr=sharedPreferences.getString("update_str","");
        Log.i(TAG,"update_str="+updateStr);
        //获取当前日期
        LocalDate today=LocalDate.now();
        Log.i(TAG,"today_date="+today);
        if(updateStr.equals(today.toString())){
            Log.i(TAG,"日期相等，不从网络获取数据");
;        }else{
            Thread t=new Thread(this);
            t.start();

        }



        //开启线程

        handler=new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                String rate="";
                //SharedPreferences sp=getSharedPreferences("webrate",ConfigActivity.MODE_PRIVATE);
                SharedPreferences.Editor editor=sharedPreferences.edit();
                if(msg.what==1){
                    rate=(String)msg.obj;
                    dollarRate= 100f/Float.valueOf(rate);
                    Log.i(TAG,"handleMessage:dollar="+dollarRate);
                    //Toast.makeText(MoneyActivity.this,"数据已更新",Toast.LENGTH_SHORT).show();
                    //保存获取的汇率数据
                    editor.putFloat("dollar_rate",Float.valueOf(dollarRate));
                    //存入当前日期
                    editor.putString("update_str",today.toString());
                    editor.apply();

                }else if(msg.what==2){
                    rate=(String)msg.obj;
                    euroRate= 100f/Float.valueOf(rate);
                    Log.i(TAG,"handleMessage:dollar="+euroRate);
                    editor.putFloat("euro_rate",Float.valueOf(euroRate));
                    editor.apply();

                }else if(msg.what==3){
                    rate=(String)msg.obj;
                    wonRate= 100f/Float.valueOf(rate);
                    Log.i(TAG,"handleMessage:dollar="+wonRate);
                    editor.putFloat("won_rate",Float.valueOf(wonRate));
                    editor.apply();
                }
                super.handleMessage(msg);
            }
        };




    }




    public void click(View v) {
        float r = 0.0f;
        if (v.getId() == R.id.b1) {
            r =dollarRate;
        } else if (v.getId() == R.id.b2) {
            r = euroRate;
        } else {
            r = wonRate;
        }
        //获取用户输入
        String str = rmb.getText().toString();
        if (str != null && str.length() > 0) {
            //计算结果
            float rmb1 = Float.valueOf(str);
            float res = rmb1 * r;
            //显示输出
            result.setText(""+res);
        } else {
            //提示用户输入
            Toast.makeText(this, "请输入RMB金额", Toast.LENGTH_SHORT).show();
        }
    }
    public void openOne(View btn){
        /*
        //打开一个页面activity
        Log.i("open","openOne");
        Intent hello=new Intent(this,MainActivity.class);//窗口对象
        Intent web=new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.jd.com"));
        Intent tel=new Intent(Intent.ACTION_DIAL,Uri.parse("tel:11111111"));
        startActivity(tel);
        */

        //打开新的窗口
        show();

    }

    @Override
//接收修改的汇率值----------------------------------------------------------
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        //写在计算页面

        if(requestCode==5&&resultCode==3){
            Bundle bundle=data.getExtras();
            dollarRate=bundle.getFloat("key_dollar1",0.1f);
            euroRate=bundle.getFloat("key_euro1",0.1f);
            wonRate=bundle.getFloat("key_won1",0.1f);
            Log.i(TAG,"onActivityResult:dollarRate="+dollarRate);
            Log.i(TAG,"onActivityResult:eurorRate="+euroRate);
            Log.i(TAG,"onActivityResult:wonRate="+wonRate);
        }

        super.onActivityResult(requestCode, resultCode, data);
    }



    private void show() {
        Intent config = new Intent(this, ConfigActivity.class)
                .putExtra("dollar_key", dollarRate)
                .putExtra("euro_key", euroRate)
                .putExtra("won_key", wonRate);
        Log.i(TAG, "openConfig:dollarRate=" + dollarRate);
        Log.i(TAG, "openConfig:eurorRate=" + euroRate);
        Log.i(TAG, "openConfig:wonRate=" + wonRate);
        //Log.i(TAG,"openConfig:dollarRate:",dollarRate);
        startActivityForResult(config, 5);
    }
    //-------------------------------------------------------菜单---------------------------------
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.mymenu,menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if(item.getItemId()==R.id.menu_set){
            show();
        }
        return super.onOptionsItemSelected(item);
    }
    //-------------------------------------------------------菜单---------------------------------


    //-----------------------------------------子线程-------------------------------
    @Override
    public void run() {
        Log.i(TAG, "run: ......");
        Document doc = null;
        try {
            doc = Jsoup.connect("http://www.usd-cny.com/icbc.htm").get();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Log.i(TAG, "title:" + doc.title());
        Element table = doc.getElementsByTag("table").first();
        Log.i(TAG, "table=" + table);

        /*
        //欧元汇率
        Element tr14 = table.getElementsByTag("tr").get(14);
        Element tr14_td3 = tr14.getElementsByTag("td").get(3);
        Log.i(TAG, "run:tr14_td3 text=" + tr14_td3.text());
        Message msg_euro=handler.obtainMessage(2,"欧元汇率");
        //handler.sendMessage(msg_euro);
        //美元汇率
        Element tr3 = table.getElementsByTag("tr").get(3);
        Element tr3_td3 = tr3.getElementsByTag("td").get(3);
        Log.i(TAG, "run:tr3_td3 text=" + tr3_td3.text());
        //Message msg_dollor=handler.obtainMessage(1,tr3_td3.text());
        //handler.sendMessage(msg_dollor);
        //韩元汇率
        Element tr21 = table.getElementsByTag("tr").get(21);
        Element tr21_td3 = tr21.getElementsByTag("td").get(3);
        Log.i(TAG, "run:tr21_td3 text=" + (tr21_td3.text()));
        //Message msg_won=handler.obtainMessage(3,tr21_td3.text());
        //handler.sendMessage(msg_won);

         */

        Elements trs = table.getElementsByTag("tr");
        for (Element tr : trs) {
            Elements tds = tr.getElementsByTag("td");
            Log.i(TAG,"run:tds="+tds);

            if (tds.size() > 0) {
                String str = tds.get(0).text();
                Log.i(TAG, "run: str=" + str);
                String val = tds.get(3).text();
                Log.i(TAG, "run: val=" + val);

                if (str.equals("美元")) {
                    Log.i(TAG, "run: str1=" + str + "=>" + val);

                    Message msg = handler.obtainMessage(1, val);
                    handler.sendMessage(msg);
                } else if (str.equals("欧元")) {
                    Log.i(TAG, "run: str2=" + str + "=>" + val);
                    Log.i(TAG, "run: 欧元=" + val);

                    Message msg = handler.obtainMessage(2, val);
                    handler.sendMessage(msg);
                } else if (str.equals("韩币")) {
                    Log.i(TAG, "run: str3=" + str + "=>" + val);
                    Log.i(TAG, "run: 韩元=" + val);


                    Message msg = handler.obtainMessage(3,val);
                    handler.sendMessage(msg);
                }
                //Message msg = handler.obtainMessage(3,val);
                //handler.sendMessage(msg);
            }


        }
    }












         /*
        for (Element td : tds) {
            Log.i(TAG, "run:td=" + td);
            Log.i(TAG, "run:td text=" + td.text());
            Log.i(TAG, "run:td html=" + td.html());
        }
        //按行获取,在行里面获取单独的td
        Elements trs = table.getElementsByTag("tr");
        for (Element tr : trs) {
            Log.i(TAG, "run:tr=" + tr);
            Log.i(TAG, "run:tr text=" + tr.text());
            Log.i(TAG, "run:tr html=" + tr.html());
        }
/*
        for (int row = 1; row <= 22; row++) {
            Element tr = table.getElementsByTag("tr").get(row);
            Element tr_td3 = tr.getElementsByTag("td").get(3);
            Log.i(TAG, "run:tr_td3 text=" + tr_td3.text());

        }

 */

/*
                    //返回消息到主线程

 */









        /*
        for(Element tr1_td:tr1.getElementsByTag("td")){
            Log.i(TAG,"run:tr1_td="+tr1_td);
            Log.i(TAG,"run:tr1_td text="+tr1_td.text());
            Log.i(TAG,"run:tr1_td html="+tr1_td.html());

        }
        */


        //耗时操作
        /*
        URL url=null;
        try {
            url=new URL("http://www.usd-cny.com/icbc.htm");
            HttpURLConnection http=(HttpURLConnection)url.openConnection() ;
            InputStream in=http.getInputStream();
            String html=inputStream2String(in);
            Log.i(TAG, "run: html="+html);

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

         */

        /*
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Log.i(TAG, "run: after 3s");



    }


    }

         */


    private String inputStream2String(InputStream inputStream)throws IOException{
        //将输入流转换为String
        final int bufferSize=1024;
        final char[] buffer=new char[bufferSize];
        final StringBuilder out=new StringBuilder();
        Reader in =new InputStreamReader(inputStream,"gb2312");
        while (true){
            int rsz=in.read(buffer,0,buffer.length);
            if(rsz<0){
                break;
            }
            out.append(buffer,0,rsz);
        }
        return  out.toString();

    }
}


